import HttpUtil from './HttpUtil'
import StrUtil from './StrUtil'

export default class OssUtil {
    /**
     * 上传单文件
     * @param path
     * 
     * 头像上传示例
     * 
        <button open-type="chooseAvatar" @chooseavatar="onChooseAvatar" style="width: 200rpx; height: 200rpx">
            <image :src="conf.avatarUrl" style="width: 200rpx; height: 200rpx"></image>
        </button>
        
        const conf = reactive({
            avatarUrl:
                'https://thirdwx.qlogo.cn/mmopen/vi_32/tIVibas8kFuIjMuPkXlSKzkFyxQD1hXRr6lwGrJD3ZQ3w6r2ibWzeZeShsKkkSibWR83CApqyib4fiaSoSic9VzeZAHw/132'
        })
        
        const onChooseAvatar = async (data: any) => {
            const url = await OssUtil.uploadOne(data.target.avatarUrl)
            if (typeof url === 'string') conf.avatarUrl = url
        }
     *
     *
     * 
     * 选择图片示例
     * 
     * 
        <button @click="chooseImage">上传</button>
        
        const chooseImage = () => {
            uni.chooseImage({
                success: async (res) => {
                    res.tempFilePaths
                    for (let i = 0; i < res.tempFilePaths.length; i++) {
                        const path = res.tempFilePaths[i]
                        const url = await OssUtil.uploadOne(path)
                    }
                }
            })
        }
     */
    static uploadOne(path: string): Promise<boolean | string> {
        const domain = 'http://luoye6.c44.cc'
        return new Promise(async (_res) => {
            const suf = StrUtil.getImageExtension(path)
            if (!suf) {
                _res(false)
                return
            }
            let token: any = await HttpUtil.get({
                url: '/oss/getToken',
                resource: true
            })

            if (typeof token !== 'string') {
                _res(false)
                return
            }

            uni.uploadFile({
                url: 'https://up-z2.qiniup.com',
                filePath: path,
                name: 'file',
                formData: {
                    token,
                    key: 'icon/' + Date.now() + '.' + suf
                },
                success: function (res: any) {
                    console.log(res)
                    if (res.statusCode === 200) {
                        const data = JSON.parse(res.data)
                        _res(domain + '/' + data.key)
                    }
                    _res(false)
                },
                fail: function (error: any) {
                    console.log(error)
                    _res(false)
                }
            })
        })
    }
}
